<template>
  <div class="xtx-pagination">
    <!-- {{pager.btnArr}} -->
    <a  @click="changePage(currCount-1)" href="javascript:;" :class="{disabled:currCount <= 1}">上一页</a>
    <span v-if="pager.start > 1">...</span>
    <a @click="changePage(i)" v-for="i in pager.btnArr" :key="i" href="javascript:;" :class="{active:currCount === i}">{{i}}</a>
    <span v-if="pager.end < pager.currTotalPage">...</span>
    <a @click="changePage(currCount+1)" href="javascript:;" :class="{disabled:currCount >= pager.currTotalPage}">下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props:{
    counts:{
        type:Number
    },
    pageSize:{
        type:Number
    },
    pages:{
        type:Number
    },
    currCounts:{
        type:Number
    }
  },
  setup(props,{emit}){
    // 按钮个数
    const count = 5
    // 当前页数
    const currCount = ref(1)
    // 总条数
    const totalSize = ref(100)
    // 一页多少条
    const onePage =  ref(10)
    // 计算属性:为了得到按钮数组
    const pager = computed(()=>{
        // 得到总页数
        const currTotalPage = Math.ceil(totalSize.value/onePage.value)
        const oldCount = Math.floor(count/2)
        // 起始页
        let start = currCount.value - Math.floor(count/2)//7
        // 末尾页
        let end = start + count - 1//11
        if(start < 1){
            start = 1
            end = start + count - 1 > currTotalPage ?  currTotalPage : start + count - 1
        }
        if(end >= currTotalPage){
            end = currTotalPage//10
            start = end - count + 1 < 1 ? 1 : end - count + 1//10-5+1=6
           
        }
        // 按钮数组
        const btnArr = []
        for(let i = start; i <= end; i++){
            btnArr.push(i)
        }
        return {start, end, btnArr,currTotalPage,oldCount}
    })
    watch(props,()=>{
        // currCount.value = props.currCounts
        // totalSize.value = props.counts
        // onePage.value =props.pageSize
        // console.log('改变了')
    },{immediate:true})
    // 改变分页的函数
    const changePage = (newVal) => {
        // 改变页码
        if(currCount.value !== newVal){
            currCount.value = newVal
        }
        emit('change-Page',newVal)
    }
    return {pager, currCount, changePage}
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>